﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace ModernUILogViewer.Elements.Helpers
{
    [Obsolete("Use TextChangedCommandDelay", true)]
    public class TextBoxInputDelayer : TextBox
    {
        #region DependencyProperty

        public static readonly DependencyProperty OnTextChangedCommandProperty =
           DependencyProperty.RegisterAttached("OnTextChangedCommand", typeof(ICommand),
           typeof(TextBoxInputDelayer), new FrameworkPropertyMetadata(OnTextChangedCommandPropertyChanged));

        public static readonly DependencyProperty CommandParameterProperty =
           DependencyProperty.RegisterAttached("CommandParameter", typeof(object),
           typeof(TextBoxInputDelayer));

        #endregion

        #region Properties

        public Double Delay
        {
            get;
            set;
        }

        public ICommand OnTextChangedCommand
        {
            get { return (ICommand)GetValue(OnTextChangedCommandProperty); }
            set { SetValue(OnTextChangedCommandProperty, value); }
        }

        public object CommandParameter
        {
            get { return (object)GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }
        
        #endregion
        
        #region Methods

        private void DelayCommand()
        {
            var input = Observable.FromEventPattern<TextChangedEventArgs>(this, "TextChanged")
                .Select(evt => ((TextBox)evt.Sender).Text)
                .Throttle(TimeSpan.FromSeconds(Delay))
                .DistinctUntilChanged()
                .ObserveOnDispatcher()
                .Subscribe((o) =>
                {
                    OnTextChangedCommand.Execute(CommandParameter);
                });
        }
        
        #endregion

        #region Metadata

        static void OnTextChangedCommandPropertyChanged(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            TextBoxInputDelayer textBox = sender as TextBoxInputDelayer;

            textBox.DelayCommand();
        }
        
        #endregion
    }
}
